package com.example.emos.wx.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.emos.wx.db.dao.TbDeptDao;
import com.example.emos.wx.db.dao.TbUserDao;
import com.example.emos.wx.db.pojo.MessageEntity;
import com.example.emos.wx.db.pojo.TbUser;
import com.example.emos.wx.exception.EmosException;
import com.example.emos.wx.service.UserService;
import com.example.emos.wx.task.MessageTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
@Scope("prototype")
public class UserServiceImpl implements UserService {

    @Value("${wx.app-id}")
    private String appId;

    @Value("${wx.app-secret}")
    private String appSecret;

    @Autowired
    private TbUserDao userDao;

    @Autowired
    private MessageTask messageTask;

    @Autowired
    private TbDeptDao deptDao;

    private String getOpenId(String code){
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        HashMap map = new HashMap();
        map.put("appid", appId);
        map.put("secret", appSecret);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");

        String response = HttpUtil.post(url, map);
        //将响应的值转换为json字符串
        JSONObject json = JSONUtil.parseObj(response);
        String openid = json.getStr("openid");
        if (openid == null || openid.length() == 0){
            throw new RuntimeException("临时登录凭证错误");
        }
        return openid;
    }

    @Override
    public int registerUser(String registerCode, String code, String nickname, String photo) {
        //判断是不是超级管理员
        if ("000000".equals(registerCode)){
            //查询超级管理员账户是否已经绑定
            boolean bool = userDao.haveRootUser();
            if (!bool){
                //还没有超级管理员账户的话就 把该用户绑定在超级管理员用户下
                String openId = getOpenId(code);
                HashMap<String, Object> param = new HashMap<>();

                param.put("openId", openId);
                param.put("nickname", nickname);
                param.put("photo", photo);
                param.put("role","[0]");
                param.put("status", 1);
                param.put("createTime", new Date());
                param.put("root", true);
                userDao.insert(param);
                int id = userDao.searchIdByOpenId(openId);

                MessageEntity entity = new MessageEntity();
                entity.setSenderId(0);
                entity.setSenderName("系统消息");
                entity.setUuid(IdUtil.simpleUUID());
                entity.setMsg("欢迎注册成为超级管理员，请及时更新你的员工个人信息");
                entity.setSendTime(new Date());
                messageTask.sendAsync(id+"",entity);
                return id;
            }
            else {
                //主要体现在业务上出现问题
                throw new EmosException("无法绑定超级管理员账号");
            }
        }
        //todo 此处还有其他判断
        else {
            //普通员工的注册


        }

        return 0;
    }


    @Override
    public Set<String> searchUserPermissions(int userId) {
        Set<String> permissions =  userDao.searchUserPermissions(userId);
        return permissions;
    }

    @Override
    public Integer login(String code) {
        //先获取到openId
        String openId = getOpenId(code);
        Integer userId = userDao.searchIdByOpenId(openId);
        if (userId == null){
            throw new EmosException("你还没注册不能登录");
        }
//        messageTask.receiveAsync(userId+"");

        return userId;
    }

    @Override
    public TbUser searchById(int userId) {
        TbUser user = userDao.searchById(userId);
        return user;
    }

    @Override
    public String searchUserHiredate(int userId) {
        String hiredate = userDao.searchUserHiredate(userId);
        return hiredate;
    }

    @Override
    public HashMap searchUserSummary(int userId) {
        HashMap map = userDao.searchUserSummary(userId);
        return map;
    }

    @Override
    public ArrayList<HashMap> searchUserGroupByDept(String keyword) {
        //查询部门数据
        ArrayList<HashMap> list_1 = deptDao.searchDeptMembers(keyword);
        //查询用户数据
        ArrayList<HashMap> list_2 = userDao.searchUserGroupByDept(keyword);
        //取出每一个部门的id
        for (HashMap map1 : list_1){
            long deptId = (long) map1.get("id");
            ArrayList members = new ArrayList();
            //查询每一个员工
            for (HashMap map2 : list_2){
                long id = (long) map2.get("deptId");
                if (deptId == id){
                    members.add(map2);
                }
            }
            map1.put("members",members);
        }
        return list_1;
    }

    @Override
    public ArrayList<HashMap> searchMembers(List param) {
        ArrayList<HashMap> list = userDao.searchMembers(param);

        return list;
    }


}
